package com.zdd.spring.framework.beans.support;

import com.zdd.spring.framework.beans.config.MyBeanDefinition;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @version 1.0
 * @Author: carl
 * @Description: 配置文件读取工具
 * @Date: Create in 14:19 2020/4/9 0009
 */
public class MyBeanDefinitionReader {

    // 缓存扫描结果
    private List<String> registryBeanClasses = new ArrayList<String>();

    private Properties contextConfig = new Properties();

    public MyBeanDefinitionReader(String[] configLocations) {
        //加载配置文件
        doLoadConfig(configLocations[0]);

        //扫描配置文件中的配置的相关的类
        doScanner(contextConfig.getProperty("scanPackage"));
    }

    public Properties getConfig(){ return this.contextConfig;}

    public List<MyBeanDefinition> loadBeanDefinitions(){
        List<MyBeanDefinition> result = new ArrayList<MyBeanDefinition>();
        try {
            for(String className : registryBeanClasses){
                Class<?> beanClass = Class.forName(className);
                if(beanClass.isInterface()){continue;}
                result.add()
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private void doScanner(String scanPackage) {
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.","/"));
        File classPath = new File(url.getFile());

        for(File file: classPath.listFiles()){
            if(file.isDirectory()){
                doScanner(scanPackage + "." + file.getName());
            }else{
                if(!file.getName().endsWith(".class")){continue;}
                // 获取全类名 = 包名.类名
                String className = scanPackage+ "." + file.getName().replaceAll(".class","");
                registryBeanClasses.add(className);
            }
        }

    }

    private void doLoadConfig(String configLocation) {

        InputStream is = this.getClass().getClassLoader().getResourceAsStream(configLocation.replaceAll("classpath:","");)
        try {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
